<template>
  <CardContainer class="calendar">
    <template v-slot:header>
      <div class="calendar-title">
        <span :class="{'active-span':type==='solar'}" @click="changeTypeHandle('solar')">公历</span>
        <span :class="{'active-span':type==='lunar'}" @click="changeTypeHandle('lunar')">农历</span>
      </div>
      <div class="calendar-fun">
        <div>
          <svg-icon icon-class="#shuangjiantouzuo" @click="preYearHandle" />
          <svg-icon icon-class="#xiangzuo" @click="preMonthHandle" />
        </div>
        <div class="title-year-month">
          <span>{{ dateTitle }}</span>
        </div>
        <div>
          <svg-icon icon-class="#xiangyou" @click="nextMonthHandle" />
          <svg-icon icon-class="#shuangjiantouyou" @click="nextYearHandle" />
        </div>
      </div>
    </template>
    <el-calendar ref="elCalender" v-model="date" :first-day-of-week="7">
      <template v-slot:dateCell="{date, data}">
        <div :class="['date-cell',{'date-cell-active': data.isSelected}]">
          <span v-show="type==='solar'">{{ solar2lunar(date).cDay }}</span>
          <span v-show="type==='lunar'" :class="monthClass(solar2lunar(date))">{{ lunar2Cn(solar2lunar(date)) }}</span>
        <!-- <svg-icon v-show="data.isSelected" icon-class="#zhengquewancheng" /> -->
        </div>
      </template>
    </el-calendar>
  </CardContainer>
</template>
<script>
import CardContainer from '@/components/CardContainer'
import { calendar } from '@/utils/calendar'
import { parseTime } from '@/utils'
export default {
  name: 'Calendar',
  components: {
    CardContainer
  },
  props: {
    value: {
      type: [String],
      default: () => ''
    },
    type: {
      type: [String],
      default: 'solar'
    }
  },
  data() {
    return {
      dateTD: '',
      date: '',
      calender: null,
      charList: {
        0: '零',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        10: '十',
        11: '十一',
        12: '十二',
        _2: '廿'
      }
    }
  },
  computed: {
    dateTitle() {
      if (!this.dateTD) return ''
      const obj = this.solar2lunar(this.dateTD)
      if (this.type !== 'solar') {
        let t = ''
        obj.lYear.toString().split('').forEach(e => {
          t += this.charList[e]
        })
        return `${t} 年 ${this.charList[obj.lMonth]} 月`
      }
      return `${obj.cYear} 年 ${obj.cMonth} 月`
    }
  },
  watch: {
    date(nValue, oValue) {
      if (!nValue) {
        this.dateTD = new Date()
        this.$emit('input', '')
      }
      // 更新标题
      this.dateTD = this.date
      const d = this.solar2lunar(nValue)
      if (this.type === 'solar') {
        this.$emit('input', this.formatData(d.date))
      } else {
        this.$emit('input', this.formatData(d.lunarDate))
      }
    },
    value: {
      handler(nValue) {
        if (!nValue) {
          this.dateTD = new Date()
          return
        }
        if (this.type === 'solar') {
          this.date = new Date(nValue)
        } else {
          this.date = new Date(this.lunar2solar(nValue).date)
        }
        // 更新标题
        this.dateTD = this.date
      },
      immediate: true
    },
    type: {
      handler() {
        if (!this.type) {
          this.$emit('update:type', 'solar')
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.calender = this.$refs.elCalender
  },
  methods: {
    preYearHandle() {
      const date = this.date || new Date()
      const temp = new Date(date.getFullYear() - 1, date.getMonth(), date.getDate())
      const day = parseTime(temp, '{y}-{m}')
      this.calender.pickDay(`${day}-01`)
    },
    preMonthHandle() {
      this.calender.selectDate('prev-month')
    },
    nextYearHandle() {
      const date = this.date || new Date()
      const temp = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate())
      const day = parseTime(temp, '{y}-{m}')
      this.calender.pickDay(`${day}-01`)
    },
    nextMonthHandle() {
      this.calender.selectDate('next-month')
    },
    // 公历转阴历
    solar2lunar(date) {
      let y = ''
      let m = ''
      let d = ''
      if (date instanceof Date) {
        y = date.getFullYear()
        m = date.getMonth() + 1
        d = date.getDate()
      } else {
        const di = date.split('-')
        y = di[0]
        m = di[1]
        d = di[2]
      }
      return calendar.solar2lunar(y, m, d)
    },
    // 阴历转公历
    lunar2solar(date) {
      let y = ''
      let m = ''
      let d = ''
      if (date instanceof Date) {
        y = date.getFullYear()
        m = date.getMonth() + 1
        d = date.getDate()
      } else {
        const di = date.split('-')
        y = di[0]
        m = di[1]
        d = di[2]
      }
      let isLeapMonth = calendar.leapMonth(y)
      isLeapMonth = isLeapMonth !== 0 && isLeapMonth === m
      return calendar.lunar2solar(y, m, d, isLeapMonth)
    },
    // 阴历转换为中文
    lunar2Cn(date) {
      let day = date.lDay
      day = day.toString()
      if (day === 1 || day === '1') {
        return `${date.lMonth}`
      }
      if (/^\d$/.test(day) || day === 10 || day === '10') {
        return `初${this.charList[day]}`
      }
      const _day = parseInt(day)
      if (_day < 20) {
        return `${this.charList[10]}${this.charList[day[1]]}`
      }
      if (_day === 20) {
        return `${this.charList['2']}${this.charList[10]}`
      }
      if (_day < 30) {
        return `${this.charList['_2']}${this.charList[day[1]]}`
      }
      if (_day === 30) {
        return `${this.charList['3']}${this.charList[10]}`
      }
    },
    // 阴历月份加粗
    monthClass(date) {
      let day = date.lDay
      day = day.toString()
      if (day === 1 || day === '1') {
        return `month`
      } else {
        return ''
      }
    },
    // 农历公历切换
    changeTypeHandle(type) {
      if (type === this.type) {
        return
      }
      this.date = ''
      this.$emit('update:type', type)
    },
    formatData(date) {
      const t = []
      for (const item of date.split('-')) {
        if (item.toString().length <= 1) {
          t.push(`0${item}`)
        } else {
          t.push(item)
        }
      }
      return t.join('-')
    }
  }
}
</script>
<style lang='scss'>
@import '@/styles/mixin.scss';
.calendar{
  padding:0 20px;
  border: 1px solid rgba(121, 121, 121, 1);
  // 隐藏el-calendar默认头部
  .el-calendar__header{
    display: none !important;
  }
  // 去掉默认高度
  .el-calendar-table .el-calendar-day{
    height: auto;
  }
  // 修改单元格样式
  .el-calendar__body{
    padding: 12px 20px 0px;
    .current,.prev,.next{
      border: none !important;
      .el-calendar-day{
        @include flex($justify:center,$align:center);
      }
    }
    .prev,.next{
      .date-cell{
        color: rgba(222,206,207,1) !important;
      }
    }
    .is-selected,.el-calendar-day:hover{
      background-color: initial !important;
    }
  }
  .calendar-title{
    margin-bottom: 20px;
    span{
      color: rgba(0,0,0,.85);
      font-size: 16px;
      font-weight: 400;
      cursor: pointer;
      user-select: none;
    }
    &>span:first-of-type{
      margin-right: 35px;
    }
    .active-span{
      font-size: 18px;
      font-weight: 700;
    }
  }
  .calendar-fun{
    @include flex($justify:space-between);
    &>div:not(.title-year-month){
      &>*{
        cursor: pointer;
        user-select: none;
      }
      &>*:first-child{
        margin-right: 20px;
      }
    }
    & .title-year-month{
      color: rgba(99,99,99,1);
      font-size: 16px;
    }

  }
  .date-cell{
    line-height: 1em;
    color: rgba(99,97,148,1);
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: white;
    @include flex($align:center, $justify:center);
  }
  .date-cell-active{
    background-color: rgba(57,195,148,1);
    color: red;
    & .month{
      color: red;
    }
  }
  .el-calendar-table .el-calendar-day{
    height: auto;
  }
  .month{
    font-weight: 700;
    transform: scale(2);
    color: #39c394;
  }

}
</style>
